package core

import "fmt"

type BlockChain struct {
	Blocks              []*Block
	Nodes               []string
	CurrentTransactions []Transaction
	Length              int64
}

func CreateBlockChain() *BlockChain {
	GenesisBlock := GenerateGenesisBlock()
	blockChain := BlockChain{}
	blockChain.Append(&GenesisBlock)
	return &blockChain
}
func (bc *BlockChain) SendBlock(data string) {
	preBlock := bc.Blocks[len(bc.Blocks)-1]
	newBlock := CreateNewBlock(*preBlock, data)
	bc.Append(&newBlock)
}

func (bc *BlockChain) Append(newBlcok *Block) {
	if len(bc.Blocks) < 1 {
		bc.Blocks = append(bc.Blocks, newBlcok)
	}
	if isvalid(*newBlcok, *bc.Blocks[len(bc.Blocks)-1]) {
		bc.Blocks = append(bc.Blocks, newBlcok)
	}
}

func isvalid(newBlock Block, oldBlock Block) bool {
	if newBlock.Index-1 != oldBlock.Index {
		return false
	}

	if newBlock.PreBlockHash != oldBlock.Currhash {
		return false
	}

	if newBlock.Currhash != CreateBlockHash(newBlock) {
		return false
	}

	return true
}

func (bc *BlockChain) PrintBlockChain() {
	for _, block := range bc.Blocks {
		fmt.Printf("Index is : %d\n", block.Index)
		fmt.Printf("preBlcokHash is : %s\n", block.PreBlockHash)
		fmt.Printf("Currhash is : %s\n", block.Currhash)
		fmt.Printf("TimeStemp is : %d\n", block.TimeStemp)
		fmt.Printf("Data is : %s\n", block.Data)
	}
}
